<script setup>
// FPS分析(首次合格率)
import { ref, onMounted } from 'vue'

const processData = apiData => {
	const brands = [...new Set(apiData.map(item => item.brand))]
	const metrics = ['qualifiedRate', 'avgEfficiency', 'avgUtilization', 'planCompletionRate', 'defectRate']

	return {
		brands,
		indicators: metrics.map(metric => ({
			name: {
				qualifiedRate: '合格率',
				avgEfficiency: '平均生产效率',
				avgUtilization: '平均资源利用率',
				planCompletionRate: '计划完成率',
				defectRate: '缺陷率',
			}[metric],
			max: Math.max(100, Math.ceil(Math.max(...apiData.map(d => d[metric])) * 1.2)),
		})),
		seriesData: brands.map(brand => {
			const brandData = apiData.filter(d => d.brand === brand).reduce((acc, cur) => cur, {})
			return {
				name: brand,
				value: metrics.map(metric => brandData?.[metric] || 0),
			}
		}),
	}
}

const fetchData = async () => {
	try {
		const response = await fetch('http://localhost/api/ads-fps')
		const apiData = await response.json()
		const { brands, indicators, seriesData } = processData(apiData)

		chartOption.value.radar.indicator = indicators
		chartOption.value.legend.data = brands
		chartOption.value.series[0].data = seriesData
	} catch (error) {
		console.error('数据获取失败:', error)
	}
}

onMounted(() => {
	fetchData()
})

const chartOption = ref({
	backgroundColor: 'transparent', // 透明背景以适配深色主题
	tooltip: {
		trigger: 'item',
		valueFormatter: function (value) {
			return value + '%'
		},
	},
	legend: {
		data: [],
		orient: 'vertical',
		right: '15%',
		top: 'middle',
		// 图例文字颜色设置为白色
		textStyle: {
			color: 'white',
		},
	},
	radar: {
		center: ['40%', '50%'],
		radius: '70%',
		axisName: { color: '#aaa' }, // 坐标名称颜色
		splitLine: { lineStyle: { color: 'rgba(100, 100, 100, 0.5)' } }, // 分割线
		axisLine: { lineStyle: { color: 'rgba(100, 100, 100, 0.5)' } }, // 轴线
		indicator: [],
	},
	series: [
		{
			name: '品牌指标对比',
			type: 'radar',
			symbol: 'rect',
			symbolSize: 5,
			lineStyle: { width: 1, type: 'dashed' }, // 加粗线条
			areaStyle: { opacity: 0.2 }, // 半透明填充
			data: [],
		},
	],
})
</script>

<template>
	<v-chart theme="chalk" :option="chartOption" />
</template>

<style scoped></style>
